<template>
  <section>
    <h2>学生增加</h2>
    <el-form
      ref="myForm"
      :model="formData"
      status-icon
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="学生姓名" prop="name">
        <el-input v-model="formData.name" type="text" maxlength="10" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电话号码" prop="tel">
        <el-input type="tel" v-model="formData.tel" />
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-select v-model="formData.major" placeholder="请选择专业">
          <el-option label="" value="" />
          <el-option label="JAVA" value="JAVA" />
          <el-option label="WEB" value="WEB" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(myForm)">Submit</el-button>
        <el-button @click="resetForm(myForm)">Reset</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script lang="ts" setup>
import { reactive, ref,defineEmits } from "vue";
import type { FormInstance, FormRules } from "element-plus";

const formData = reactive<any>({});
const myForm = ref<FormInstance>();

const emits = defineEmits(["update:modelValue"]);

let id = 100;

const rules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度只能是2到10位", trigger: "blur" },
  ],
  tel: [
    { required: true, message: "请输入姓名号码", trigger: "blur" },
    { min: 11, max: 11, message: "电话号码应该是11位", trigger: "blur" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  major: [{ required: true, message: "请选择专业", trigger: "blur" }],
});

function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.validate((valid, fields) => {
    if (valid) {
      emits("update:modelValue",{...formData,id: id ++})
      formEl.resetFields();
    }
  });
}

// 清空表单
function resetForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.resetFields();
}
</script>

<style scoped lang="scss">
</style>